document.addEventListener("beforeload", handleBeforeLoadEvent, true);
document.addEventListener("dblclick", handleDblclick, true);
if (document.URL.indexOf("reader/view") != -1) {
    document.addEventListener('keypress', handleKeypress, true);
}

function loadContent(event) {
	const element = event.target;
	element.className = element.className.replace(" blocked-content", "");
	element.removeEventListener("click", loadContent, true);
	element.allowedToLoad = true;
	var nextSibling = element.nextSibling;
	var parentNode = element.parentNode;
	parentNode.removeChild(element);
	parentNode.insertBefore(element, nextSibling);

	event.stopPropagation();
	event.preventDefault();
}

function handleBeforeLoadEvent(event) {
	const element = event.target;
	if (element.allowedToLoad)
		return;

	if (safari.self.tab.canLoad(event, { url: event.url, nodeName: element.nodeName }))
		return;

	event.preventDefault();
	element.className += " blocked-content";
	element.addEventListener("click", loadContent, true);
}

function handleDblclick(event) {
    var sel = event.view.getSelection();
    if (!sel.rangeCount) { return; }
    if (!/\b(https?)|\.[a-z]{2,4}\b/i.test(sel.toString()))
        return;
    var endn = sel.focusNode;
    if (endn.nodeType != Node.TEXT_NODE) { return; }
    var nodetxt = endn.textContent;
    var extoffset = nodetxt.substr(sel.focusOffset, 90).search(/[^-\w+&@#\/%?=~_|!:,.;]/);
    if (extoffset < 0) {
        extoffset = nodetxt.length;
    } else {
        extoffset += sel.focusOffset;
    }
    var urltxt = nodetxt.substring(sel.anchorOffset, extoffset);
    if (!/\b(https?:)/i.test(urltxt))
        urltxt = 'http://' + urltxt;
    safari.self.tab.dispatchMessage('openBackgroundTab', urltxt);
}

function handleKeypress(event) {
    var tag = event.target.tagName;
    if (tag === 'TEXTAREA' || tag === 'INPUT' || tag === 'SELECT') {
        return;
    }

    // Catch 'v', but not ctrl-v or cmd-v.
    if (event.which === 118 && !event.ctrlKey && !event.metaKey) {
        var current = document.getElementById('current-entry');
        if (!current) {
            return;
        }
        event.stopPropagation();
        event.preventDefault();
        safari.self.tab.dispatchMessage('openBackgroundTab',
                current.getElementsByTagName('a')[0].getAttribute('href'));
    }
}
